package script.msg.user;

import com.df.gameserver.modules.user.UserManager;
import com.df.gameserver.modules.user.entity.Player;
import com.df.gameserver.net.MsgSend;
import com.df.script.IScript;
import com.msg.User;
import io.netty.channel.Channel;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;


public class C2S_LoginScript implements IScript {


    private  final Integer scriptId = -452433618;


    @Override
    public void excute(Object... args) {
        handleMsg((Channel) args[0], (User.C2S_Login) args[1]);
    }

    @Override
    public Integer getScriptId() {
        return scriptId;
    }

    private void handleMsg(Channel channel, User.C2S_Login msg) {
        String uuid = UUID.randomUUID().toString();
        Player player = new Player();
        player.setId(uuid);

        Attribute<String> attr = channel.attr(UserManager.getInstance().userIdKey);
        attr.set(uuid);

        //给自己返回消息
        User.S2C_LoginResp.Builder result = User.S2C_LoginResp.newBuilder();

        User.Player.Builder ownPlayerBuilder = User.Player.newBuilder();
        ownPlayerBuilder.setId(uuid);
        ownPlayerBuilder.setX(player.getX());
        ownPlayerBuilder.setY(player.getY());

        Collection<Player> values = UserManager.getInstance().getId2user().values();
        List<User.Player> otherPlayers = values.stream().map(p -> {
            User.Player.Builder b = User.Player.newBuilder();
            b.setId(p.getId());
            b.setX(p.getX());
            b.setY(p.getY());
            return b.build();
        }).collect(Collectors.toList());

        result.setOwn(ownPlayerBuilder.build());
        result.addAllOthers(otherPlayers);
        UserManager.getInstance().addUser(player);
        UserManager.getInstance().addChannel(player,channel);
        //给别人发
        User.S2C_AddPlayer.Builder toOther = User.S2C_AddPlayer.newBuilder();
        toOther.setNewPlayer(ownPlayerBuilder.build());




        MsgSend.send(channel,result);
        MsgSend.broadcastAll(toOther, Arrays.asList(uuid));

    }

}
